import { Injectable } from "@nestjs/common";
import { Like, Repository } from "typeorm";
import { ResultData } from "@/common/utils/result";
import { instanceToPlain } from "class-transformer";
import { InjectRepository } from "@nestjs/typeorm";
import { User } from "@/modules/user/entities/user.entity";
import { UpdateUserDto } from "@/modules/user/dto/update-user.dto";

export class CrudService {
	private readonly Repository;
	
	constructor(Repository) {
		this.Repository = "";
	}
	
	async create(createDto) {
		return ResultData.ok(instanceToPlain(await this.Repository.save(createDto)));
	}
	
	async findAll(findAllDto) {
		const { page, size, username, status } = findAllDto;
		const take = size || 15;
		const skip = ((page || 1) - 1) * take;
		const where = {
			...(status ? { status } : null),
			...(username ? { username: Like(`%${username}%`) } : null)
		};
		return ResultData.rowOk(instanceToPlain(await this.Repository.findAndCount({
			order: {
				id: "DESC"
			},
			where,
			relations: {
				roles: true
			},
			skip,
			take
		})));
	}
	
	async findOne(id: number) {
		ResultData.ok(instanceToPlain(await this.Repository.findOneById(id)));
	}
	
	async update(id: number, updateDto) {
		return ResultData.ok(await this.Repository.update(id, updateDto), "更新成功");
	}
	
	async remove(id: number) {
		return ResultData.ok(await this.Repository.delete(id), "删除成功");
	}
}
